﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using DonViNganh;
namespace HDVN5.Control
{
    public partial class ThongTinDoanSinh : System.Web.UI.UserControl
    {

        private Int32 MaDonVi = 0;
        private string phuongThuc = "";
        private DonViNganh.DoanSinh Adoansinh= null;
        private HDVN5.DanhMucDataContext dbDanhMuc = null;

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
               
                MaDonVi = Convert.ToInt32(Session["MADONVIID"].ToString());
                bingDropDownList();
                MaDonViNganh.Value = MaDonVi.ToString();
                phuongThuc = Request.QueryString["method"].ToString();
                TrangThai.Value = phuongThuc;

                HDVN5.SOQUANLYDONVI soquanlydonvi = dbDanhMuc.SOQUANLYDONVIs.Single(p => p.MASO == MaDonVi);
                int nganh = (int)soquanlydonvi.NGANHID;

                HDVN5.DANHMUCNGANH danhmucnganh = dbDanhMuc.DANHMUCNGANHs.Single(p => p.ID == nganh);

                if (danhmucnganh != null)
                {
                    TuoiMax.Value = danhmucnganh.TUOIMAX.ToString();
                    TuoiMin.Value = danhmucnganh.TUOIMIN.ToString();

                }
                if (phuongThuc.Equals("add"))
                {
                    string madoansinhmoi = CapPhatCacMa.capMaDoanSinh(Convert.ToInt32(MaDonViNganh.Value), DateTime.Now.Date);
                    lblMaSoDoanSinh.Text = madoansinhmoi;
                }
                else if (phuongThuc.Equals("edit"))
                {
                    string madoansinhedit = Request.QueryString["madoansinh"].ToString();
                    lblMaSoDoanSinh.Text = madoansinhedit;
                    bingFromCSDLToTextBox(Convert.ToInt64(madoansinhedit));
                }
            }
        }

        /// <summary>
        /// Upload hinh anh
        /// </summary>
        /// <param name="FileName"></param>
        private void UploadFile(string FileName)
        {
            string imgPath = "/Images/DoanSinh/"+FileName;
            string realPath = Server.MapPath(imgPath);

            if (System.IO.File.Exists(realPath))
            {
                System.IO.File.Delete(realPath);
            }
            else
            {
                if (UploadHinHAnh.PostedFile != null || UploadHinHAnh.PostedFile.FileName != "")
                {
                    imgPath = "/Images/DoanSinh/"+UploadHinHAnh.PostedFile.FileName;
                    realPath = Server.MapPath(imgPath);
                    UploadHinHAnh.SaveAs(realPath);
                    
                }
            }
        }
        private void themTuyenHua(bool tuyenhua)
        {
            if (tuyenhua == true)
            {
                string option = Request.Form["opt"];
                string madonvituyenhua="";
                if (option == "1")
                {
                    madonvituyenhua = MaDonViNganh.Value;
                }
                else if (option == "2")
                {
                    madonvituyenhua = DonViNganhSe.SelectedValue.ToString();
                }

                DonViNganhDataContext dbs = new DonViNganhDataContext();
                DonViNganh.DOANSINH_TUYENHUA doansinhTuyenHua = new DonViNganh.DOANSINH_TUYENHUA();
                doansinhTuyenHua.DONVITUYENHUAID = Convert.ToInt32(madonvituyenhua);
                doansinhTuyenHua.MADOANSINH = Convert.ToInt64(lblMaSoDoanSinh.Text);
                doansinhTuyenHua.NGAYTUYENHUA = NgayTuyenHua.Text;
                doansinhTuyenHua.TENTRUONG = TruongNhanTuyenHua.Text;
                doansinhTuyenHua.NGAYVAOSO = DateTime.Now.Date;
              
                dbs.DOANSINH_TUYENHUAs.InsertOnSubmit(doansinhTuyenHua);
                dbs.SubmitChanges();

            }
        }
        private bool themSuaDoanSinh()
        {
            bool eb = true;
            try
            {
                phuongThuc = Request.QueryString["method"].ToString();
                if (phuongThuc.Equals("add"))
                {

                    Adoansinh = new DoanSinh();
                    DonViNganh.DOANSINH newDoanSinh = new DOANSINH();
                    bingDoanSinhToCSDL(newDoanSinh);
                    Adoansinh.themMoiDoanSinh(newDoanSinh, Session["LOGIN_ID"].ToString(), Convert.ToInt32(MaDonViNganh.Value), Convert.ToInt64(lblMaSoDoanSinh.Text), UploadHinHAnh.PostedFile.FileName.ToString());
                    themTuyenHua(chkTuyenHua.Checked);
                    updateMaDoanSinhToQLMDOANSINH(lblMaSoDoanSinh.Text, MaDonViNganh.Value);

                }
                else if (phuongThuc.Equals("edit"))
                {
                    DonViNganh.DonViNganhDataContext db = new DonViNganhDataContext();
                    try
                    {
                        DOANSINH ds = db.DOANSINHs.Single(p => p.MADOANSINH == Convert.ToInt64(lblMaSoDoanSinh.Text));
                        bingDoanSinhToCSDL(ds);
                        db.SubmitChanges();
                    }
                    catch (Exception ex)
                    {
                        eb = false;
                        throw new Exception(ex.Message);
                        
                    }
                }
            }
            catch
            {
                eb= false;
            }

            return eb;
        }

        /// <summary>
        /// Sổ các danh mục để lựa chọn
        /// </summary>
        private void bingDropDownList()
        {
            dbDanhMuc = new DanhMucDataContext();
            var qTonGiao = from tongiao in dbDanhMuc.DANHMUCTONGIAOs select tongiao;
            var qDanToc = from dantoc in dbDanhMuc.DANHMUCDANTOCs select dantoc;
            var qNgheNghiep = from nghenghiep in dbDanhMuc.DANHMUCNGHENGHIEPs select nghenghiep;
            var qTinhThanh = from tinhthanh in dbDanhMuc.DANHMUCTINHTHANHs select tinhthanh;
            TonGiao.DataSource = qTonGiao.ToArray();
            TonGiao.DataBind();

            DanToc.DataSource = qDanToc.ToArray();
            DanToc.DataBind();

            NgheNghiep.DataSource = qNgheNghiep.ToArray();
            NgheNghiep.DataBind();

            TinhThanhPho.DataSource = qTinhThanh.ToArray();
            TinhThanhPho.DataBind();
        }

        /// <summary>
        /// Bing truoc vao thuc the roi moi luu
        /// lam vay cho do moi tay 
        /// </summary>
        /// <param name="doansinh"></param>
        /// 
        private void bingDoanSinhToCSDL(DOANSINH doansinh)
        {
            doansinh.MADOANSINH = Convert.ToInt64(lblMaSoDoanSinh.Text);
            doansinh.HOLOT = HoLot.Text.Trim() + " " + Dem.Text.Trim() + " ";
            doansinh.TEN = Ten.Text.Trim();
            doansinh.NGAYSINH = DateTime.Parse(NgaySinh.Text);
            doansinh.NOISINH = NoiSinh.Text;
            doansinh.GIOITINH = chkNam.Checked ? 1 : 0;
            doansinh.TONGIAOID = Convert.ToInt32(TonGiao.SelectedValue);
            doansinh.DANTOCID = Convert.ToInt32(DanToc.SelectedValue);
            doansinh.DIACHI = DiaChi.Text;
            doansinh.SODIENTHOAI = SoDTNha.Text;
            doansinh.SODIENTHOAIDD = SoDTDD.Text;
            doansinh.EMAIL = Email.Text;
            doansinh.SOCMND = SoCMND.Text;
            doansinh.NGAYCAP =changeToDate(NgayCap.Text);
            doansinh.NOICAP = NoiCap.Text;
            doansinh.NGHENGHIEPID = Convert.ToInt32(NgheNghiep.SelectedValue);
            doansinh.NGAYTHAMGIA = TextBox1.Text;
            doansinh.HOTENCHA = TenCha.Text;
            doansinh.SODTCHA = SoDTLienLac.Text;
            doansinh.HOTENME = TenMe.Text;
            doansinh.SODTME = SoDTMe.Text;
            doansinh.NGAYTAO = DateTime.Now.Date;
            doansinh.TAIKHOANTAO = Session["LOGIN_ID"].ToString();
            doansinh.DATUYENHUA = chkTuyenHua.Checked ? 1 : 0;
        }

        /// <summary>
        /// Bing du lieu vao page de sua
        /// </summary>
        /// <param name="MaDoanSinh"></param>
        private void bingFromCSDLToTextBox(Int64 MaDoanSinh)
        {
            DonViNganh.DonViNganhDataContext dbEdit = new DonViNganhDataContext();
            DOANSINH doansinh = dbEdit.DOANSINHs.Single(p => p.MADOANSINH == MaDoanSinh);

            lblMaSoDoanSinh.Text= doansinh.MADOANSINH.ToString();
            HoLot.Text= doansinh.HOLOT;
            Ten.Text = doansinh.TEN;
            NgaySinh.Text = doansinh.NGAYSINH.Value.ToShortDateString();
            NoiSinh.Text=doansinh.NOISINH ;
            chkNam.Checked = doansinh.GIOITINH==1?chkNam.Checked:false;
            TonGiao.SelectedValue=doansinh.TONGIAOID.ToString();
             DanToc.SelectedValue=doansinh.DANTOCID.ToString() ;
            DiaChi.Text=doansinh.DIACHI  ;
            SoDTNha.Text=doansinh.SODIENTHOAI  ;
            SoDTDD.Text=doansinh.SODIENTHOAIDD  ;
            Email.Text=doansinh.EMAIL  ;
            SoCMND.Text=doansinh.SOCMND  ;
           NgayCap.Text= doansinh.NGAYCAP!=null?doansinh.NGAYCAP.Value.ToShortDateString():""  ;
            NoiCap.Text=doansinh.NOICAP;
           NgheNghiep.SelectedValue= doansinh.NGHENGHIEPID.ToString() ;
           TextBox1.Text= doansinh.NGAYTHAMGIA  ;
           TenCha.Text= doansinh.HOTENCHA  ;
           SoDTLienLac.Text= doansinh.SODTCHA  ;
           TenMe.Text= doansinh.HOTENME ;
           SoDTMe.Text= doansinh.SODTME ;
           TuyenHua.Value = doansinh.DATUYENHUA.ToString();
           chkTuyenHua.Checked = doansinh.DATUYENHUA == 1;
           if (doansinh.DATUYENHUA == 1)
           {
               chkTuyenHua.Enabled = false;
           }
        }

        /// <summary>
        /// Thay doi kieu du lieu
        /// </summary>
        /// <param name="value"></param>
        /// <returns></returns>
        private DateTime? changeToDate(string value)
        {

            try
            {
                return Convert.ToDateTime(value);
            }
            catch
            {
                return null;
            }
        }

        /// <summary>
        /// Luu doan sinh
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnLuu_Click(object sender, EventArgs e)
        {
            bool update = themSuaDoanSinh();
            string clienMess = "";
            if (update == true)
            {
                clienMess = "<script> alert('Thêm / Sửa Đoàn sinh thành công') </script>";
            }
            else
            {
                clienMess = "<script> alert('Thêm / Sửa Đoàn sinh không thành công') </script>";
            }

            Response.Write(clienMess);
            Response.Redirect("/DonViNganhPage/DonViNganhHomePage.aspx");

        }

        protected void TinhThanhPho_SelectedIndexChanged(object sender, EventArgs e)
        {
            dbDanhMuc = new DanhMucDataContext();
            int tinh = Convert.ToInt32(TinhThanhPho.SelectedItem.Value);
            var qLienDoanThuocTinh = from liendoan in dbDanhMuc.SOQUANLYDONVIs
                                     where liendoan.TINHTHANH == tinh
                                     select liendoan;

            LienDoan.DataSource = qLienDoanThuocTinh.ToArray();
            LienDoan.DataBind();


        }

        protected void LienDoan_SelectedIndexChanged(object sender, EventArgs e)
        {
      
        }


        private void updateMaDoanSinhToQLMDOANSINH(string madoansinh, string madonvi)
        {

           

        }

    }
}